package com.example.news.ui;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;
import static android.content.ContentValues.TAG;

import static com.example.news.activity.LoginActivity.isNetConnection;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.news.MainActivity;
import com.example.news.R;
import com.example.news.activity.LoginActivity;
import com.example.news.adapter.CollectRecycleAdapter;
import com.example.news.adapter.NewsDataBindingAdapter;
import com.example.news.bean.NewsBean;
import com.example.news.helper.GsonUtils;
import com.example.news.helper.Mp3helper;
import com.example.news.helper.Ttshelper;
import com.example.news.helper.gethttp;
import com.example.news.databinding.FragmentHomeBinding;
import androidx.databinding.DataBindingUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class HomeFragment extends Fragment {

    public String ip;
    public Ttshelper tshelper=new Ttshelper();
    public HomeFragment() {
        // Required empty public constructor
    }



    @Override
    public void onViewCreated(View view,Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        checknetwork();
        ip=getActivity().getString(R.string.ip);
        Mp3helper mp3helper=new Mp3helper(getActivity(),R.raw.home1);
        mp3helper.play(false);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_home, container, false);
    }
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        OnBackPressedCallback callback = new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
            }
        };
    }
    private float lastTouchX;
    private float lastTouchY;
    // 实现回调接口，定义触摸后的操作
    private MainActivity.MyTouchListener myTouchListener = new MainActivity.MyTouchListener() {
        @Override
        public void onTouch(MotionEvent ev) {
            switch (ev.getAction()) {
                // 手指点击屏幕时，记录当前的X坐标和Y坐标
                case MotionEvent.ACTION_DOWN:
                    lastTouchX = ev.getX();
                    lastTouchY = ev.getY();

                    break;
                /*
                 * 手指在屏幕上滑动的时候，获取当前的X坐标和Y坐标，然后和起始位置的坐标做对比，
                 * 如果移动的距离超过1，显示该图片
                 */
                case MotionEvent.ACTION_MOVE:
                    float disX = ev.getX() - lastTouchX;
                    float disY = ev.getY() - lastTouchY;
                    Log.i(TAG, "onTouch: Y="+disY);
                    Log.i(TAG, "onTouch: X="+disX);
                    if (disX <- 400) {
                        NavController controller = Navigation.findNavController(getActivity(),R.id.nav_host_fragment_activity_main);
                        controller.navigate(R.id.action_homeFragment_to_userFragment);
                    }else if(disX >200){
                    }else if(disY>350){
                        Intent mIntent = new Intent();
                        mIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                        mIntent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
                        startActivityForResult(mIntent, 200);
                    }else if(disY <-350){

                    }
                    break;
                default:
                    break;
            }
        }
    };
    public Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch(msg.what)
            {
                case 1 : {
                    Log.i(":", msg.obj.toString());
                }
                case 2 :break;
            }
        }
    };
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent
            data) {
        if (requestCode == 520) {
            if (resultCode == RESULT_OK) {
                Bitmap bp = (Bitmap) data.getExtras().get("data");
                try {
                    getwords(bitmapToBase64(bp));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else if (resultCode == RESULT_CANCELED) {
                Toast.makeText(getActivity(), "Cancelled", Toast.LENGTH_LONG).show();
            }
        }
    }
    public void getwords(String base64) throws InterruptedException {
        String url="http://"+ip+":8080/user/getword?base64="+base64;
        gethttp ghttp=new gethttp(url,handler);
        ghttp.start();
        ghttp.join();
    }
    private static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    @Override
    public void onResume() {
        super.onResume();
        // 在onResume里面注册回调
        ((MainActivity) this.getActivity())
                .registerMyTouchListener(myTouchListener);
    }
    public void tos(String line)
    {
        Toast.makeText(getContext(), line, Toast.LENGTH_SHORT).show();
    }
    public void checknetwork() {
        if (!isNetConnection(getContext())) {
            tshelper.play(getContext(), "当前无网络，请连接网络", 0);
        }
        if (ActivityCompat.checkSelfPermission(getContext(), "android.permission.INTERNET") == 1 || ActivityCompat.checkSelfPermission(getContext(), "android.permission.ACCESS_NETWORK_STATE") == 1) {
            tshelper.play(getContext(), "网络权限未开启，请让您身边的朋友替您开启", 0);
        }
    }
    @Override
    public void onStop() {
        tshelper.conselplay();
        super.onStop();
    }
}